package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.VendoutResultContract;
import com.lkd.dao.VendingMachineDao;
import com.lkd.entity.*;
import com.lkd.exception.LogicException;
import com.lkd.http.vo.CreateVMReq;
import com.lkd.service.*;
import com.lkd.utils.UUIDUtils;
import com.lkd.vo.Pager;
import com.lkd.vo.SkuVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class VendingMachineServiceImpl extends ServiceImpl<VendingMachineDao, VendingMachineEntity> implements VendingMachineService {

    @Resource
    private NodeService nodeService;

    @Resource
    private ChannelService channelService;

    @Resource
    private VmTypeService vmTypeService;

    @Resource
    private VendingMachineDao vendingMachineDao;
    @Resource
    private VendoutRunningService vendoutRunningService;

    @Override
    public List<VendingMachineEntity> getByNodeId(Long nodeId) {
        List<VendingMachineEntity> list = vendingMachineDao.findByNodeId(nodeId);
        return list;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean add(CreateVMReq vendingMachine) {
        VendingMachineEntity vendingMachineEntity = new VendingMachineEntity();
        vendingMachineEntity.setNodeId(Long.valueOf(vendingMachine.getNodeId()));
        vendingMachineEntity.setVmType(vendingMachine.getVmType());
        NodeEntity nodeEntity = nodeService.getById(vendingMachine.getNodeId());
        if (nodeEntity == null) {
            throw new LogicException("所选点位不存在");
        }
        //复制属性
        BeanUtils.copyProperties(nodeEntity, vendingMachineEntity);
        vendingMachineEntity.setCreateUserId(Long.valueOf(vendingMachine.getCreateUserId()));
        vendingMachineEntity.setInnerCode(UUIDUtils.getUUID());
        vendingMachineEntity.setClientId(UUIDUtils.generateClientId(vendingMachineEntity.getInnerCode()));
        this.save(vendingMachineEntity);
        //创建货道数据
        createChannel(vendingMachineEntity);
        return true;
    }


    /**
     * 创建货道
     *
     * @param vm
     * @return
     */
    private boolean createChannel(VendingMachineEntity vm) {
        VmTypeEntity vmType = vmTypeService.getById(vm.getVmType());
        List<ChannelEntity> channelList = Lists.newArrayList();
        for (int i = 1; i <= vmType.getVmRow(); i++) {
            for (int j = 1; j <= vmType.getVmCol(); j++) {
                ChannelEntity channel = new ChannelEntity();
                channel.setChannelCode(i + "-" + j);
                channel.setCurrentCapacity(0);
                channel.setInnerCode(vm.getInnerCode());
                channel.setLastSupplyTime(vm.getLastSupplyTime());
                channel.setMaxCapacity(vmType.getChannelMaxCapacity());
                channel.setVmId(vm.getId());
                channelList.add(channel);
            }
        }
        channelService.saveBatch(channelList);
        return true;
    }


    @Override
    public boolean update(Long id, Long nodeId) {
        VendingMachineEntity vm = this.getById(id);
        if (vm.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("改设备正在运营");
        }
        NodeEntity nodeEntity = nodeService.getById(nodeId);
        BeanUtils.copyProperties(nodeEntity, vm);
        return this.updateById(vm);
    }


    @Override
    public Pager<String> getAllInnerCodes(boolean isRunning, long pageIndex, long pageSize) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<VendingMachineEntity> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageIndex, pageSize);

        QueryWrapper<VendingMachineEntity> qw = new QueryWrapper<>();
        if (isRunning) {
            qw.lambda()
                    .select(VendingMachineEntity::getInnerCode)
                    .eq(VendingMachineEntity::getVmStatus, 1);
        } else {
            qw.lambda()
                    .select(VendingMachineEntity::getInnerCode)
                    .ne(VendingMachineEntity::getVmStatus, 1);
        }
        this.page(page, qw);
        Pager<String> result = new Pager<>();
        result.setCurrentPageRecords(page.getRecords().stream().map(VendingMachineEntity::getInnerCode).collect(Collectors.toList()));
        result.setPageIndex(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setTotalCount(page.getTotal());

        return result;
    }

    @Override
    public Pager<VendingMachineEntity> query(Long pageIndex, Long pageSize, Integer status, String innerCode) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<VendingMachineEntity> page
                = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            queryWrapper.eq(VendingMachineEntity::getVmStatus, status);
        }
        if (!Strings.isNullOrEmpty(innerCode)) {
            queryWrapper.likeLeft(VendingMachineEntity::getInnerCode, innerCode);
        }
        this.page(page, queryWrapper);

        return Pager.build(page);
    }


    @Override
    public VmVO findByInnerCode(String innerCode) {
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VendingMachineEntity::getInnerCode, innerCode);
        VendingMachineEntity vm = this.getOne(queryWrapper);
        VmVO vmVO = new VmVO();
        BeanUtils.copyProperties(vm, vmVO);
        //地址
        vmVO.setNodeAddr(vm.getNode().getAddr());
        //名称
        vmVO.setNodeName(vm.getNode().getName());
        return vmVO;
    }


    @Override
    public boolean updateStatus(String innerCode, Integer status) {
        try {
            UpdateWrapper<VendingMachineEntity> uw = new UpdateWrapper<>();
            uw.lambda()
                    .eq(VendingMachineEntity::getInnerCode, innerCode)
                    .set(VendingMachineEntity::getVmStatus, status);
            this.update(uw);

        } catch (Exception ex) {
            log.error("updateStatus error,innerCode is " + innerCode + " status is " + status, ex);
            return false;
        }
        return true;
    }


    @Override
    public List<SkuVO> getSkuListByInnerCode(String innerCode) {
        //获取货道列表
        List<ChannelEntity> channelList = channelService.getChannelesByInnerCode(innerCode).stream()
                .filter(c -> c.getSkuId() > 0 && c.getSku() != null).collect(Collectors.toList());
        //获取有商品的库存余量
        Map<SkuEntity, Integer> skuMap = channelList.stream()
                .collect(Collectors.groupingBy(
                        ChannelEntity::getSku,
                        Collectors.summingInt(ChannelEntity::getCurrentCapacity)));//对库存数求和
        return skuMap.entrySet().stream().map(entry -> {
                    SkuEntity sku = entry.getKey(); //查询商品
                    SkuVO skuVO = new SkuVO();
                    BeanUtils.copyProperties(sku, skuVO);
                    skuVO.setImage(sku.getSkuImage());//图片
                    skuVO.setCapacity(entry.getValue());
                    skuVO.setRealPrice(sku.getPrice());//真实价格
                    return skuVO;
                }).sorted(Comparator.comparing(SkuVO::getCapacity).reversed())  //按库存量降序排序
                .collect(Collectors.toList());
    }

    @Override
    public Boolean hasCapacity(String innerCode, Long skuId) {
        var qw = new LambdaQueryWrapper<ChannelEntity>();
        qw
                .eq(ChannelEntity::getInnerCode, innerCode)
                .eq(ChannelEntity::getSkuId, skuId)
                .gt(ChannelEntity::getCurrentCapacity, 0);
        return channelService.count(qw) > 0;
    }

    /**
     * 补货
     *
     * @param supply
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean supply(SupplyContract supply) {
        //更新最后的补货时间
        LambdaQueryWrapper<ChannelEntity> wrapper = new LambdaQueryWrapper<>();
        //根据售货机编号查询
        wrapper.eq(ChannelEntity::getInnerCode, supply.getInnerCode());
        //查询出所有的货道(机器本身的货道数)
        List<ChannelEntity> list = channelService.list(wrapper);
        //要补货的货道
        List<SupplyChannel> supplyData = supply.getSupplyData();
        //定义list用于手机每次循环更新后的数据,用于最后批量更新
        List<ChannelEntity> channelList = new ArrayList<>(supplyData.size());

        for (ChannelEntity channelEntity : list) {
            for (SupplyChannel supplyDatum : supplyData) {
                if (channelEntity.getChannelCode().equals(supplyDatum.getChannelId())) {
                    //判断当前货道的容量
                    int num = channelEntity.getCurrentCapacity() + supplyDatum.getCapacity();
                    if (num > channelEntity.getMaxCapacity()) {
                        throw new LogicException("超出货到最大容量");
                    }
                    //更新容量
                    channelEntity.setCurrentCapacity(num);
                    //更新补货时间
                    channelEntity.setLastSupplyTime(LocalDateTime.now());
                    channelList.add(channelEntity);
                    break;
                }
            }
        }
        //批量更新
        channelService.updateBatchById(channelList);
        //更新机器的上次补货时间   货道补货时间与机器补货时间相同
        update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                .eq(VendingMachineEntity::getInnerCode, supply.getInnerCode())
                .set(VendingMachineEntity::getLastSupplyTime, LocalDateTime.now()));
        return true;
    }

    /**
     * 处理出货结果
     *
     * @param vendoutResultContract
     * @return
     */
    @Override
    public boolean vendoutResult(VendoutResultContract vendoutResultContract) {
        //接收售货机终端发过来的出货结果
        //如果出货结果异常，则回滚库存
        if(!vendoutResultContract.isSuccess()){
            log.info(vendoutResultContract.getInnerCode()+"出货异常");
            //回滚库存
            ChannelEntity channelInfo = channelService.getChannelInfo(vendoutResultContract.getInnerCode(), vendoutResultContract.getVendoutData().getChannelCode());
            channelInfo.setCurrentCapacity(channelInfo.getCurrentCapacity()+1);
            channelService.updateById(channelInfo);
            return false;
        }else{
            //如果出货成功则 将出货记录表（tb_vendout_running）的status更改为true
            LambdaQueryWrapper <VendoutRunningEntity> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(VendoutRunningEntity::getOrderNo,vendoutResultContract.getVendoutData().getOrderNo());
            VendoutRunningEntity runningEntity = vendoutRunningService.getOne(wrapper);
            if(runningEntity==null){
                return false;
            }
            runningEntity.setStatus(true);
            vendoutRunningService.updateById(runningEntity);
        }
        return true;
    }
}
